package com.orangelife.mobile.login.activity;

import java.util.HashMap;
import java.util.Map;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;


import com.common.sp.UserSp;
import com.curry.android.http.HttpUtil;
import com.curry.android.util.DialogHelper;
import com.curry.android.util.IntentHelper;
import com.curry.android.util.JSONHelper;
import com.curry.android.util.StringUtil;
import com.curry.orangelife.mobile.R;
import com.orangelife.mobile.app.application.ExitApplication;
import com.orangelife.mobile.common.activity.OrangeLifeBaseActivity;
import com.orangelife.mobile.common.biz.JSONRequest;
import com.orangelife.mobile.constants.Constant;
import com.thirdsdk.jpush.JPushTagHelper;
import com.orangelife.mobile.main.activity.MainTablActivity;
import com.orangelife.mobile.util.CryptoDES;
import com.orangelife.mobile.util.ToastHelper;
import com.umeng.update.UmengUpdateAgent;

/**
 * 登录
 *
 * @author yw
 */
@Deprecated
public class LoginActivity extends OrangeLifeBaseActivity {
    /** 登录标题、注册、忘记密码 */
    private TextView tvRegistor, tvVisitor, tvForgetPwd;
    /** 提交按钮 */
    private Button btnSubmit;
    /** 电话号码、密码 */
    private EditText etPhone, etPwd;
    private Dialog dialog;
    private boolean isVistor = false;

    HashMap<String, Object> hashMap;

    @Override
    protected void onCreate(Bundle paramBundle) {
        super.onCreate(paramBundle);
        ExitApplication.getInstance().addActivity(this);
        setContentView(R.layout.activity_login);
        UmengUpdateAgent.setDefault();
        UmengUpdateAgent.update(this);
        initView();
        findView();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!StringUtil.isContainBlank(UserSp.getRegPhone())) {
            etPhone.setText(UserSp.getRegPhone());
        } else {
            etPhone.setText("");
        }

    }

    /** 点击隐藏输入法 */
    public void hideInput(View v) {
        InputMethodManager imm = (InputMethodManager) this
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
    }

    private void findView() {
        /* 给注册设置监听器，跳转到注册界面 */
        tvRegistor.setOnClickListener(clickListener);
        tvVisitor.setOnClickListener(clickListener);
        btnSubmit.setOnClickListener(clickListener);
        tvForgetPwd.setOnClickListener(clickListener);
    }

    private void initView() {
        tvRegistor = (TextView) findViewById(R.id.tv_register);
        tvVisitor = (TextView) findViewById(R.id.tv_visitor);
        tvForgetPwd = (TextView) findViewById(R.id.tv_forget_pwd);
        btnSubmit = (Button) findViewById(R.id.btn_submit);
        etPhone = (EditText) findViewById(R.id.et_phone);
        etPwd = (EditText) findViewById(R.id.et_new_pwd);
		/* 从本地取数据 */
        String phoneNumber = UserSp.getRegPhone();
        if (phoneNumber != null) {
            etPhone.setText(phoneNumber);
        }

    }


    View.OnClickListener clickListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent intent = new Intent();
            switch (v.getId()) {
                case R.id.tv_register:
                    intent.setClass(LoginActivity.this, RegisterActivity.class);
                    startActivity(intent);
                    break;
                case R.id.tv_visitor:
                    if (!isConnected()) {
                        return;
                    }
                    try {
                        String phone = CryptoDES.encrypt("orangelife",
                                Constant.DES_KEY);
                        String password = StringUtil.md5("666666");
                        dialog = DialogHelper.getInstance().createLoadingDialog(
                                LoginActivity.this,
                                getResources().getString(R.string.login_logining));
                        dialog.show();
                        isVistor = true;
//					sendRequestForLogin(phone, password);
                        IntentHelper.getInstances().getIntent(LoginActivity.this, MainTablActivity.class);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                case R.id.btn_submit:
                    String phone = etPhone.getText().toString();
                    String password = etPwd.getText().toString();

                    if (!StringUtil.isPhone(phone)) {
                        ToastHelper.getInstance()._toast(
                                getResources().getString(
                                        R.string.phone_number_error));
                    } else if (StringUtil.isContainBlank(phone)) {
                        ToastHelper.getInstance()._toast(
                                getResources()
                                        .getString(R.string.phone_number_null));
                    } else if (StringUtil.isContainBlank(password)) {
                        ToastHelper.getInstance()._toast(
                                getResources().getString(R.string.password_null));
                    } else {
                        if (!isConnected()) {
                            return;
                        }
                        try {
                            phone = CryptoDES.encrypt(phone, Constant.DES_KEY);
                            password = StringUtil.md5(password);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        dialog = DialogHelper.getInstance().createLoadingDialog(
                                LoginActivity.this,
                                getResources().getString(R.string.login_logining));
                        dialog.show();
                        isVistor = false;
                        sendRequestForLogin(phone, password);
                    }
                    break;
                case R.id.tv_forget_pwd:
                    IntentHelper.getInstances().getIntent(LoginActivity.this,
                            ResetPwdActivity.class);
                    break;
                default:
                    break;
            }
        }
    };

    /** 处理后天返回的数据 */
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        @SuppressWarnings("unchecked")
        public void handleMessage(android.os.Message msg) {
            if (msg.obj == null)
                return;
            switch (msg.what) {
                case Constant.WHAT_ERROR_HTTP:
                    ToastHelper.getInstance()._toast(String.valueOf(msg.obj));
                    dialog.dismiss();
                    break;

                case 110:/* 登录 */
                    if (msg.obj != null) {
                        HashMap<String, Object> map = (HashMap<String, Object>) JSONHelper
                                .jsonToMap(String.valueOf(msg.obj));
                        if (map != null) {
                            int errCode = Integer.parseInt(map.get(
                                    Constant.RESULT_KEY).toString());
                            String errInfo = String.valueOf(map
                                    .get(Constant.RESULT_MESSAGE_KEY));
                            if (errCode == Constant.RESULT_SUCCESS) {
                                HashMap<String, Object> map1 = (HashMap<String, Object>) map
                                        .get("entity");
                                hashMap = new HashMap<String, Object>();
                                hashMap.put("loginID", map1.get("loginID").toString());
                                hashMap.put("loginName", map1.get("loginName").toString());
                                hashMap.put("loginType", map1.get("loginType").toString());
                                hashMap.put("registerTime", map1.get("registerTime").toString());
							/* 昵称的单独存储 */
                                String nickName = (String) map1.get("nickname");
                                if (!isVistor) {
                                    ToastHelper.getInstance()._toast(
                                            getResources().getString(
                                                    R.string.login_success));
                                }
							/* 用户账号和密码的储存 */
                                String phoneNumber = etPhone.getText().toString();
                                String passWord = etPwd.getText().toString();
                                IntentHelper.getInstances().getIntent(LoginActivity.this,
                                        MainTablActivity.class);
                                JPushTagHelper.getInstance().setContext(LoginActivity.this);
                                JPushTagHelper.getInstance().setTag(phoneNumber);
                                finish();
                            } else {
                                ToastHelper.getInstance()._toast(errInfo);
                            }
                        } else {
                            ToastHelper.getInstance()._toast(
                                    getResources().getString(R.string.login_fail));
                        }
                    }

                    break;
            }
            if (dialog != null) {
                dialog.dismiss();
            }
        }

    };

    /**
     * 向服务器发送登录请求
     *
     * @param mobilePhone 手机号（用户名）
     * @param password    密码
     */
    private void sendRequestForLogin(String mobilePhone, String password) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("userName", mobilePhone);
        map.put("password", password);
        map.put("loginType", "app");
        Map<String, Object> rootMap = new HashMap<String, Object>();
        rootMap.put("map", map);
        rootMap.put("url", Constant.PATH_LOGIN);
        rootMap.put("wat", 110);
        new JSONRequest(JSONRequest.POST, rootMap, handler,
                HttpUtil.ACTION_JSON);

    }

    /**
     * 重载返回键
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit();
            return false;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    /**
     * 双击退出
     */
    private boolean isExit;
    @SuppressLint("HandlerLeak")
    Handler mHandler2 = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            isExit = false;
        }

    };

    /**
     * 双击退出的方法体
     */
    public void exit() {
        if (!isExit) {
            isExit = true;
            ToastHelper.getInstance()._toast(
                    getResources().getString(R.string.double_exit));
            mHandler2.sendEmptyMessageDelayed(0, 2000);
        } else {
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_HOME);
            startActivity(intent);
            ExitApplication.getInstance().exit();
            this.finish();
        }
    }

}
